<!--
  @author:  long
  @date:    2023/3/2
  @file:    客户列表
  @require:
-->
<template>
  <div class="commercialLoan app-container">
    <!-- 客户列表主体 start -->
    <div class="">
      <el-form :model="queryForm" ref="queryFormRef" class="demo-form-inline">
        <el-row :gutter="10">
          <el-col :span="4">
            <el-form-item>
              <el-input
                v-model.trim="queryForm.customerTaxcodeOrName"
                placeholder="客户名称或编号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select
                clearable
                v-model="queryForm.status"
                placeholder="审核状态"
              >
                <el-option
                  v-for="(dict, index) in jrsd_audit_status"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select
                clearable
                v-model="queryForm.lendingBank"
                placeholder="放款银行"
              >
                <el-option
                  v-for="(dict, index) in lendingBankOptions"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select
                clearable
                v-model="queryForm.isNew"
                placeholder="是否新户"
              >
                <el-option
                  v-for="(dict, index) in is_new_finance_customer"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-date-picker
                style="width: 100%"
                v-model="applyforTime"
                type="daterange"
                start-placeholder="创建时间起"
                end-placeholder="创建时间止"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select
                clearable
                v-model="queryForm.excavationMethod"
                placeholder="客户挖掘方式"
              >
                <el-option
                  v-for="(dict, index) in customerExcavationOptions"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item>
              <el-tree-select
                style="width: 100%"
                v-model="queryForm.orgId"
                :data="companyOptions"
                :disabled="
                  userStore.user.userName != '3500015' &&
                  userStore.user.userName != '3500025'
                "
                clearable
                :props="{
                  value: 'id',
                  label: 'label',
                  children: 'children'
                }"
                placeholder="所属公司"
                value-key="id"
                filterable
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select
                v-model="queryForm.userId"
                placeholder="选择创建人"
                @focus="userInputFocus"
                :disabled="userSelectDisabled"
                class="w-full"
                clearable
              >
                <el-option
                  v-for="(item, index) in selectOptionObj['userId']"
                  :key="index"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select
                v-model="queryForm.marketingPerson"
                placeholder="选择获客人员"
                @focus="searchMarketingPersonInputFocus"
                class="w-full"
                clearable
              >
                <el-option
                  v-for="(item, index) in selectOptionObj[
                    'searchMarketingPerson'
                  ]"
                  :key="index"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!--          <el-col :span="3">-->
          <!--            <el-form-item>-->
          <!--              <el-select-->
          <!--                clearable-->
          <!--                v-model="queryForm.marketingIsAuth"-->
          <!--                placeholder="是否认证并填写营销码"-->
          <!--              >-->
          <!--                <el-option-->
          <!--                  v-for="(dict, index) in certified_status"-->
          <!--                  :label="dict.label"-->
          <!--                  :value="dict.value"-->
          <!--                  :key="index"-->
          <!--                ></el-option>-->
          <!--              </el-select>-->
          <!--            </el-form-item>-->
          <!--          </el-col>-->
          <el-col :span="6">
            <el-form-item>
              <el-date-picker
                style="width: 100%"
                v-model="lendingTime"
                type="daterange"
                start-placeholder="放款时间起"
                end-placeholder="放款时间止"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select
                clearable
                v-model="queryForm.invoiceIssueRange"
                placeholder="开票区间（近1年）"
              >
                <el-option
                  v-for="(dict, index) in invoicing_interval"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >查询
            </el-button>
            <el-button icon="RefreshLeft" @click="handleEmpty">重置</el-button>
          </el-col>
        </el-row>
      </el-form>
      <!-- 操作按钮 start-->
      <div class="pb-3 mt-3">
        <el-row>
          <el-col :span="18">
            <el-button
              type="primary"
              icon="Plus"
              @click="handleOpenDialog('handle')"
            >
              新建申贷
            </el-button>
            <el-button
              icon="Document"
              type="primary"
              @click="handleOpenDialog('approve')"
              v-hasPermi="['jrsdsh']"
              plain
            >
              审核
            </el-button>
            <el-button
              icon="EditPen"
              type="primary"
              :disabled="editDiasbled"
              plain
              @click="toUpdate"
              >编辑
            </el-button>
            <el-button
              icon="Delete"
              type="primary"
              plain
              @click="deleteCommercial"
              >删除
            </el-button>
            <el-button icon="Upload" type="primary" plain @click="exportQuery"
              >导出
            </el-button>
            <el-button
              icon="document"
              type="primary"
              plain
              @click="handleSelectCustomer('check')"
              >客户列表
            </el-button>
          </el-col>
          <el-col :span="6" class="text-right">
            <el-button icon="Refresh" circle />
            <el-button icon="Setting" circle @click="handleTableColumn" />
          </el-col>
        </el-row>
      </div>
      <!-- 操作按钮 end-->

      <!--   客户列表显示start   -->
      <el-table
        ref="tableRef"
        :data="tableData"
        border
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        @row-click="rowClick"
      >
        <el-table-column align="center" type="selection" width="55" />
        <el-table-column
          label="营销公司"
          align="center"
          min-width="100"
          show-overflow-tooltip
          prop="marketingCompany"
        ></el-table-column>
        <el-table-column
          label="创建人"
          prop="createBy"
          show-overflow-tooltip
          align="center"
          min-width="80"
        ></el-table-column>
        <el-table-column
          label="创建时间"
          align="center"
          min-width="100"
          prop="createTime"
        >
        </el-table-column>
        <el-table-column
          label="客户名称"
          align="center"
          min-width="150"
          prop="customerName"
        ></el-table-column>
        <el-table-column
          label="法人名称"
          align="center"
          min-width="80"
          prop="legalName"
        ></el-table-column>
        <el-table-column
          label="联系方式"
          align="center"
          min-width="115"
          prop="legalPhone"
        ></el-table-column>
        <el-table-column
          label="放款银行"
          align="center"
          min-width="80"
          prop="lendingBank"
        ></el-table-column>
        <el-table-column
          label="审批情况"
          align="center"
          min-width="80"
          prop="approveAmount"
        ></el-table-column>
        <el-table-column
          label="状态"
          align="center"
          min-width="80"
          prop="status"
        ></el-table-column>
        <el-table-column
          label="放款情况"
          min-width="80"
          align="center"
          prop="lendingAmount"
        ></el-table-column>
        <el-table-column
          label="获客人员"
          align="center"
          prop="marketingPerson"
        ></el-table-column>

        <el-table-column
          :label="item.label"
          align="center"
          :width="item.width"
          v-for="(item, index) in tableColumn.filter(item => item.isCheckBox)"
          :key="index"
          :show-overflow-tooltip="item.showTooltip"
        >
          <template #default="scope">
            <!--      放款时间      -->
            <span v-if="item.prop == 'lendingTime'">
              {{ scope.row.lendingStarttime.substring(0, 10) }}
            </span>

            <span v-else>{{ scope.row[item.prop] }}</span>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryForm.pageNum"
        v-model:limit="queryForm.pageSize"
        @pagination="getList"
      />
      <!--   客户列表显示end   -->
    </div>
    <!-- 客户列表主体end -->
    <!--  公共弹窗start -->
    <el-dialog
      v-model="dialogObj.visible"
      destroy-on-close
      :close-on-click-modal="false"
      :width="dialogObj.width"
      :title="dialogObj.title"
    >
      <div class="pr-20">
        <div v-if="dialogObj.type == 'handle'">
          <el-form
            :model="addOrUpdateForm"
            :rules="rules"
            ref="addOrUpdateFormRef"
            label-width="120px"
          >
            <el-form-item label="客户名称" prop="customerName">
              <el-input
                v-model="addOrUpdateForm.customerName"
                disabled
                placeholder="客户名称"
                @focus="handleSelectCustomer('select')"
              >
                <template #append>
                  <el-button
                    type="primary"
                    @click="handleSelectCustomer('select')"
                    >选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="客户税号" prop="customerTaxcode">
              <el-input
                v-model="addOrUpdateForm.customerTaxcode"
                disabled
                placeholder="客户税号"
              />
            </el-form-item>
            <el-form-item label="放款银行" prop="lendingBank">
              <el-select
                clearable
                v-model="addOrUpdateForm.lendingBank"
                placeholder="放款银行"
                class="w-full"
              >
                <el-option
                  v-for="(dict, index) in lending_bank"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="是否续贷商户" prop="isRenewalCustomer">
              <el-select
                clearable
                v-model="addOrUpdateForm.isRenewalCustomer"
                placeholder="请选择"
                class="w-full"
              >
                <el-option label="是" value="1"></el-option>
                <el-option label="否" value="0"></el-option>
                <!--                  <el-option-->
                <!--                      v-for="(dict, index) in sys_yes_no"-->
                <!--                      :label="dict.label"-->
                <!--                      :value="dict.value"-->
                <!--                      :key="index"-->
                <!--                  ></el-option>-->
              </el-select>
            </el-form-item>
            <el-form-item label="审批情况" prop="approveAmount">
              <el-input
                type="number"
                v-model="addOrUpdateForm.approveAmount"
                placeholder="审批情况"
              >
                <template #append>万元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="放款情况" prop="lendingAmount">
              <el-input
                type="number"
                placeholder="放款情况"
                v-model="addOrUpdateForm.lendingAmount"
              >
                <template #append>万元</template>
              </el-input>
            </el-form-item>
            <el-form-item label="放款时间" prop="lendingTime">
              <el-date-picker
                style="width: 100%"
                v-model="addOrUpdateForm.lendingTime"
                type="date"
                start-placeholder="放款时间起"
                end-placeholder="放款时间止"
                format="YYYY-MM-DD"
                valueFormat="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="备注">
              <el-input
                v-model="addOrUpdateForm.remark"
                :rows="3"
                type="textarea"
                show-word-limit
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-form>
        </div>
        <div v-if="dialogObj.type == 'approve'">
          <el-form modal="appreveForm" label-width="100">
            <el-form-item label="客户名称：">
              {{ appreveForm.customerName }}
            </el-form-item>
            <el-form-item label="审核状态：" required>
              <el-select v-model="appreveForm.status" placeholder="审核状态">
                <el-option
                  v-for="(dict, index) in jrsd_audit_status"
                  :label="dict.label"
                  :value="dict.value"
                  :key="index"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="备注：" v-if="false">
              <el-input
                v-model="appreveForm.remark"
                :rows="3"
                type="textarea"
                show-word-limit
                placeholder="请输入备注"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <!--   底部按钮   -->
      <template #footer>
        <el-button @click="handleCloseDialog">取消</el-button>
        <el-button type="primary" @click="dialogConfirm">确认</el-button>
      </template>
    </el-dialog>

    <!-- 客户弹出框 -->
    <el-dialog
      v-model="customerDialogObj.visible"
      destroy-on-close
      :close-on-click-modal="false"
      :width="customerDialogObj.width"
      :title="customerDialogObj.title"
      @close="customerDialogClose"
    >
      <el-row :gutter="10">
        <el-col
          v-if="customerDialogObj.type == 'list'"
          :span="24"
          class="relative"
        >
          <el-row class="mb-5" :gutter="10">
            <el-col :span="8">
              <el-input
                clearable
                v-model="customerTableObj.customerName"
                placeholder="客户名称"
              ></el-input>
            </el-col>
            <el-col :span="8">
              <el-input
                clearable
                v-model="customerTableObj.customerTaxcode"
                placeholder="客户税号"
              ></el-input>
            </el-col>
            <el-col :span="8">
              <el-button type="primary" @click="handleQueryCustomerList"
                >查询
              </el-button>
              <el-button @click="handleAddCustomer">新增客户</el-button>
            </el-col>
          </el-row>
          <el-table
            height="50vh"
            ref="tableCustomerRef"
            :data="customerTableObj.tableData"
            style="width: 100%"
            border
            highlight-current-row
            v-loading="customerTableObj.loading"
            @row-dblclick="handleCustomerRowDblclick"
            @row-click="handleCustomerRowClick"
          >
            <el-table-column
              label="创建人"
              show-overflow-tooltip
              prop="createBy"
              align="center"
            >
            </el-table-column>
            <el-table-column
              label="创建时间"
              show-overflow-tooltip
              prop="createTime"
              align="center"
            >
            </el-table-column>

            <el-table-column
              label="客户名称"
              show-overflow-tooltip
              prop="customerName"
              align="center"
            >
            </el-table-column>
            <el-table-column label="税号" align="center" prop="customerTaxcode">
            </el-table-column>
            <el-table-column
              label="行业类别"
              prop="industryTypeCode"
              align="center"
            ></el-table-column>
            <el-table-column
              label="法人"
              prop="legalName"
              align="center"
            ></el-table-column>
            <el-table-column
              label="联系电话"
              prop="legalPhone"
              align="center"
            ></el-table-column>
            <el-table-column
              label="开票区间"
              prop="invoiceIssueRange"
              align="center"
            ></el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template #default="scope">
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="handleCustomerUpdate(scope.row)"
                  >修改
                </el-button>
                <el-button
                  link
                  type="primary"
                  size="small"
                  @click="handleCustomerDel(scope.row)"
                  >删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pr-10 relative">
            <pagination
              small
              v-if="customerTableObj.total > 0"
              :total="customerTableObj.total"
              v-model:page="customerTableObj.pageNum"
              v-model:limit="customerTableObj.pageSize"
              @pagination="handleGetCustomerList"
            />
          </div>

          <div class="text-right mt-10">
            <el-button @click="customerDialogClose">取消</el-button>

            <el-button
              type="primary"
              v-if="openCustomerListType == 'select'"
              @click="customerChange"
              >确定
            </el-button>
          </div>
        </el-col>

        <!--    金融客户新增修改    -->
        <el-col :span="24" v-if="customerDialogObj.type == 'handle'">
          <template #header>{{ customerDialogObj.cardTitle }}</template>
          <el-form
            :rules="customerFormRules"
            v-loading="customerDialogObj.formLoading"
            :model="customerForm"
            label-width="150"
            ref="customerFormRef"
          >
            <el-row>
              <el-col :span="12">
                <el-form-item label="客户名称：" prop="customerName">
                  <el-input
                    placeholder="客户名称"
                    v-model="customerForm.customerName"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="客户税号：" prop="customerTaxcode">
                  <el-input
                    v-model="customerForm.customerTaxcode"
                    placeholder="客户税号"
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="行业类别：" prop="industryTypeCode">
                  <el-select
                    clearable
                    v-model="customerForm.industryTypeCode"
                    placeholder="行业类别"
                    class="w-full"
                  >
                    <el-option
                      v-for="(dict, index) in finance_customer_industry"
                      :label="dict.label"
                      :value="dict.value"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="是否新户：" prop="isNew">
                  <el-select
                    class="w-full"
                    v-model="customerForm.isNew"
                    placeholder="是否新户"
                  >
                    <el-option
                      v-for="(dict, index) in is_new_finance_customer"
                      :label="dict.label"
                      :value="dict.value"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="法人：" prop="legalName">
                  <el-input
                    v-model="customerForm.legalName"
                    placeholder="法人"
                  ></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="联系电话：" prop="legalPhone">
                  <el-input
                    v-model="customerForm.legalPhone"
                    placeholder="联系电话"
                  ></el-input>
                </el-form-item>
              </el-col>

              <!--              <el-col :span="12">-->
              <!--                <el-form-item label="营销码填写：" prop="marketingIsAuth">-->
              <!--                  <el-select-->
              <!--                    class="w-full"-->
              <!--                    v-model="customerForm.marketingIsAuth"-->
              <!--                    placeholder="营销码填写"-->
              <!--                  >-->
              <!--                    <el-option-->
              <!--                      v-for="(dict, index) in certified_status"-->
              <!--                      :label="dict.label"-->
              <!--                      :value="dict.value"-->
              <!--                      :key="index"-->
              <!--                    ></el-option>-->
              <!--                  </el-select>-->
              <!--                </el-form-item>-->
              <!--              </el-col>-->
              <el-col :span="12">
                <el-form-item label="客户挖掘方式：" prop="excavationMethod">
                  <el-select
                    class="w-full"
                    v-model="customerForm.excavationMethod"
                    placeholder="客户挖掘方式"
                  >
                    <el-option
                      v-for="(dict, index) in customer_excavation"
                      :label="dict.label"
                      :value="dict.value"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item
                  label="开票区间(近1年)："
                  prop="invoiceIssueRange"
                >
                  <el-select
                    v-model="customerForm.invoiceIssueRange"
                    placeholder="开票区间（近1年）"
                    class="w-full"
                  >
                    <el-option
                      v-for="(dict, index) in invoicing_interval"
                      :label="dict.label"
                      :value="dict.value"
                      :key="index"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="营销公司：" prop="marketingCompany">
                  <el-tree-select
                    style="width: 100%"
                    v-model="customerForm.marketingCompany"
                    :data="formCompanyOptions"
                    :props="{
                      value: 'id',
                      label: 'label',
                      children: 'children'
                    }"
                    placeholder="营销公司"
                    value-key="id"
                    filterable
                  />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="获客人员：" prop="marketingPerson">
                  <el-select
                    v-model="customerForm.marketingPerson"
                    placeholder="获客人员"
                    @focus="customerUserInputFocus"
                    class="w-full"
                  >
                    <el-option
                      v-for="(item, index) in selectOptionObj['customerUserId']"
                      :key="index"
                      :label="item.label"
                      :value="item.uuid"
                    ></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" class="text-center">
                <el-button type="primary" @click="handleCustomerSave"
                  >提交
                </el-button>
                <el-button @click="handleCancalCustomerForm">取消</el-button>
              </el-col>
            </el-row>
          </el-form>
        </el-col>
      </el-row>
    </el-dialog>

    <!--  公共弹窗end -->
    <!--  自定义列显示  -->
    <custom-column
      ref="customColumnRef"
      :columnData="tableColumn"
      @change="getUserDefinedColumn"
    ></custom-column>

    <!--  弹窗选择组件  -->
    <SelectDialog :dialog-param="dialogParam" @ok="selectData"></SelectDialog>
  </div>
</template>

<script setup name="CommercialLoan">
import { getCurrentInstance, toRaw } from 'vue'
import { useRouter } from 'vue-router'
import SelectDialog from '@/components/SelectDialog/index.vue'
import { treeselect, treeselectNoPriv } from '@/api/rsgl/zzjg'
import useUserStore from '@/store/modules/user'
import { validatePhoneTwo } from '@/utils/validate'
import CustomColumn from './modal/CustomColumn'
import {
  bizloancustomerDel,
  bizloancustomerSave,
  customerapplySaveOrUpdate,
  customerapplyUserDefined,
  customerpplyOutPutExcel,
  delCustomerapply,
  getBizloancustomerInfo,
  getBizloancustomerList,
  getCustomerapplyInfo,
  getCustomerapplyList
} from '@/api/statistical/commercialLoan'
import useCommonStore from '@/store/modules/common'
import { getTreeNodeByParam, getUniqueUserId } from '@/utils/commo'
import { getDeptStaffTreeData } from '@/api/system/dept'
import { getDictsNew } from '@/api/system/dict/data'
import useDictStore from '@/store/modules/dict'

// 通用数据store
const commonStore = useCommonStore()

const userStore = useUserStore()
const router = useRouter()

const { proxy } = getCurrentInstance()
const loading = ref(false)
const data = reactive({
  queryForm: {
    pageNum: 1,
    pageSize: 10,
    orgId: '',
    marketingIsAuth: '', //是否已营销认证
    excavationMethod: '', //客户挖掘方式
    invoiceIssueRange: '', //近1年开票区间
    status: '', //审核状态
    isRenewalCustomer: '', //是否新户
    userId: '', //归属人员
    lendingBank: '', //放款银行
    applyTime: ''
  },
  total: 0,
  tableData: [],
  lendingTime: '', //放款时间
  applyforTime: [], //申请时间
  lendingBankOptions: [], //所有银行（包含停用）
  customerExcavationOptions: [], //客户挖掘
  tableColumn: [
    // {
    //   isCheckBox: false,
    //   label: '创建时间',
    //   prop: 'createTime',
    //   width: '160',
    //   showTooltip: false,
    //   sortIndex: 1
    // },
    // {
    //   isCheckBox: false,
    //   label: '客户名称',
    //   prop: 'customerName',
    //   width: '150',
    //   showTooltip: true,
    //   sortIndex: 2
    // },
    //
    // {
    //   isCheckBox: false,
    //   label: '法人名称',
    //   prop: 'legalName',
    //   width: '130',
    //   showTooltip: false,
    //   sortIndex: 5
    // },
    // {
    //   isCheckBox: false,
    //   label: '联系方式',
    //   prop: 'legalPhone',
    //   width: '120',
    //   showTooltip: false,
    //   sortIndex: 6
    // },
    // {
    //   isCheckBox: false,
    //   label: '放款银行',
    //   prop: 'lendingBank',
    //   width: '130',
    //   showTooltip: false,
    //   sortIndex: 7
    // },
    // {
    //   isCheckBox: false,
    //   label: '审批情况',
    //   prop: 'approveAmount',
    //   width: '',
    //   showTooltip: false,
    //   sortIndex: 8
    // },
    //
    // {
    //   isCheckBox: false,
    //   label: '状态',
    //   prop: 'status',
    //   width: '120',
    //   showTooltip: false,
    //   sortIndex: 10
    // },
    // {
    //   isCheckBox: false,
    //   label: '放款情况',
    //   prop: 'lendingAmount',
    //   width: '',
    //   showTooltip: false,
    //   sortIndex: 9
    // },
    //   {
    //       isCheckBox: false,
    //       label: '获客人员',
    //       prop: 'marketingPerson',
    //       width: '',
    //       showTooltip: false,
    //       sortIndex: 11
    //   },
    {
      isCheckBox: false,
      label: '纳税人识别号',
      prop: 'customerTaxcode',
      width: '130',
      showTooltip: false,
      sortIndex: 3
    },
    {
      isCheckBox: false,
      label: '行业',
      prop: 'industryTypeCode',
      width: '80',
      showTooltip: false,
      sortIndex: 4
    },

    {
      isCheckBox: false,
      label: '放款时间',
      prop: 'lendingTime',
      width: '100',
      showTooltip: false,
      sortIndex: 12
    },
    {
      isCheckBox: false,
      label: '客户挖掘方式',
      prop: 'excavationMethod',
      width: '110',
      showTooltip: false,
      sortIndex: 13
    },
    // {
    //   isCheckBox: false,
    //   label: '是否填写营销码',
    //   prop: 'marketingIsAuth',
    //   width: '130',
    //   showTooltip: false,
    //   sortIndex: 14
    // },
    {
      isCheckBox: false,
      label: '是否新户',
      prop: 'isNew',
      width: '80',
      showTooltip: false,
      sortIndex: 15
    },
    {
      isCheckBox: false,
      label: '近一年开票区间',
      prop: 'invoiceIssueRange',
      width: '120',
      showTooltip: false,
      sortIndex: 16
    },
    {
      isCheckBox: false,
      label: '是否续贷',
      prop: 'isRenewalCustomer',
      width: '80',
      showTooltip: false,
      sortIndex: 17
    },
    {
      isCheckBox: false,
      label: '备注',
      prop: 'remark',
      width: '100',
      showTooltip: true,
      sortIndex: 18
    }
  ], //表格显示列

  dialogObj: {
    visible: false,
    title: '新建商贷',
    width: '40%',
    model: '',
    type: 'handle'
  },
  selectionData: [],
  dialogParam: {}, //弹窗组件配置
  selectOptionObj: {}, // select
  addOrUpdateForm: {},
  rules: {
    // 客户名称
    customerName: [
      { required: true, message: '请输入客户名称', trigger: 'blur' }
    ],
    // 客户税号
    customerTaxcode: [
      { required: true, message: '请输入客户税号', trigger: 'blur' }
    ],
    // 放款银行
    lendingBank: [
      { required: true, message: '请选择放款银行', trigger: 'change' }
    ],
    // 是否续贷商户
    isRenewalCustomer: [
      { required: true, message: '请选择是否续贷商户', trigger: 'change' }
    ],
    // 审批情况
    approveAmount: [
      { required: true, message: '请输入审批情况', trigger: 'blur' }
    ],
    // 放款情况
    lendingAmount: [
      { required: true, message: '请选择放款情况', trigger: 'change' }
    ],
    // 放款时间
    lendingTime: [
      { required: true, message: '请选择放款时间', trigger: 'change' }
    ]
  },
  customerFormRules: {
    // 客户名称
    customerName: [
      { required: true, message: '请输入客户名称', trigger: 'blur' }
    ],
    // 客户税号
    customerTaxcode: [
      { required: true, message: '请输入客户税号', trigger: 'blur' }
    ],
    // 行业类别
    industryTypeCode: [
      { required: true, message: '请选择行业类别', trigger: 'change' }
    ],
    // 是否新户
    isNew: [{ required: true, message: '请选择是否新户', trigger: 'change' }],
    // 法人
    legalName: [{ required: true, message: '请输入法人', trigger: 'blur' }],
    // 联系电话
    legalPhone: [
      { required: true, validator: validatePhoneTwo, trigger: 'blur' }
    ],
    // 营销码填写
    marketingIsAuth: [
      { required: true, message: '请选择营销码填写', trigger: 'change' }
    ],
    // 客户挖掘方式
    excavationMethod: [
      { required: true, message: '请选择客户挖掘方式', trigger: 'change' }
    ],
    // 开票区间
    invoiceIssueRange: [
      { required: true, message: '请选择开票区间', trigger: 'change' }
    ],
    // 营销公司
    marketingCompany: [
      { required: true, message: '请选择营销公司', trigger: 'change' }
    ],
    // 获客人员
    marketingPerson: [
      { required: true, message: '请选择获客人员', trigger: 'change' }
    ]
  },
  // 客户信息
  customerInfo: { id: '' },
  // 选择客户弹窗
  customerDialogObj: {
    visible: false,
    title: '金融客户列表',
    width: '60%',
    type: 'list',
    formLoading: false,
    cardTitle: '新增金融客户'
  },
  // 客户表格对象
  customerTableObj: {
    tableData: [],
    total: 0,
    pageSize: 10,
    pageNum: 1,
    loading: false,
    customerName: '',
    customerTaxcode: ''
  },
  //客户表单
  customerForm: {
    userId: '',
    orgId: ''
  },
  //审核表单
  appreveForm: {
    customerName: '',
    status: '',
    remark: ''
  }
})
const {
  lendingTime,
  queryForm,
  tableData,
  dialogObj,
  selectionData,
  dialogParam,
  selectOptionObj,
  total,
  addOrUpdateForm,
  rules,
  customerDialogObj,
  customerTableObj,
  customerForm,
  customerFormRules,
  tableColumn,
  appreveForm,
  applyforTime,
  customerInfo,
  lendingBankOptions,
  customerExcavationOptions
} = toRefs(data)
const {
  customer_status,
  customer_star,
  jrsd_audit_status,
  sys_yes_no,
  customer_excavation,
  certified_status,
  invoicing_interval,
  is_new_finance_customer,
  finance_customer_industry,
  lending_bank
} = proxy.useDict(
  'customer_status',
  'customer_star',
  'jrsd_audit_status', //审核状态
  'sys_yes_no',
  'customer_excavation', //客户挖掘方式
  'certified_status', //是否认证并填写营销码
  'invoicing_interval', //开票区间
  'is_new_finance_customer', //是否新户
  'finance_customer_industry', //所属行业
  'lending_bank' //放款银行
)

const companyOptions = ref([])
// 表单用营销公司数据
const formCompanyOptions = ref([])
const statusDescription = ref('') //移入公海状态备注
const openCustomerListType = ref('check') //打开客户列表类型  check:查看  select:选择
const userSelectDisabled = ref(true)
const editDiasbled = ref(false) //编辑按钮控制

const rowClick = row => {
  proxy.$refs.tableRef.toggleRowSelection(row) // 单击行切换选中状态
}

/**
 * 金融商贷导出
 */
const exportQuery = () => {
  let params = JSON.parse(JSON.stringify(queryForm.value))
  //   放款时间
  if (lendingTime.value != null && lendingTime.value.length > 0) {
    params.lendingStarttime = lendingTime.value[0] + ' 00:00:00'
    params.lendingEndtime = lendingTime.value[1] + ' 23:59:59'
  } else {
    params.lendingStarttime = undefined
    // params.lendingEndtime = undefined
  }
  // 申请时间
  if (applyforTime.value != null && applyforTime.value.length > 0) {
    params.applyTimeStart = applyforTime.value[0] + ' 00:00:00'
    params.applyTimeEnd = applyforTime.value[1] + ' 23:59:59'
  } else {
    params.applyTimeStart = undefined
    params.applyTimeEnd = undefined
  }
  // params.orgId =  userStore.user.orgId != 484 ? userStore.user.orgId : 484
  delete params.applyTime
  delete params.lendingTime
  console.info('params', params)

  proxy.downLoadByUrl(
    '/customer/bizloancustomer/outPutExcel',
    params,
    '金融商贷导出数据.xlsx'
  )
}

/**
 * 删除数据
 */
function deleteCommercial() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要删除的数据')
    return
  }
  proxy.$modal
    .confirm('是否确认删除选中的数据-？')
    .then(res => {
      let ids = selectionData.value
        .map(item => {
          return item.id
        })
        .join(',')
      console.info('ids', ids)
      const params = {
        ids
      }
      delCustomerapply(params).then(res => {
        proxy.$modal.msgSuccess(res.msg)
        getList()
      })
    })
    .catch(() => {})
}

/**
 * 客户选择 编辑弹窗关闭事件
 */
const customerDialogClose = () => {
  customerDialogObj.value.visible = false
  handleCancalCustomerForm()
  customerInfo.value = { id: '' }
  customerTableObj.value = {
    tableData: [],
    total: 0,
    pageSize: 10,
    pageNum: 1,
    loading: false,
    customerName: '',
    customerTaxcode: ''
  }
}

/**
 * 自定义显示列项
 */
const handleTableColumn = () => {
  proxy.$refs.customColumnRef.handleDialogOpen()
}

/**
 * 客户双击选择
 */
const handleCustomerRowDblclick = row => {
  if (openCustomerListType.value == 'select') {
    addOrUpdateForm.value.customerId = customerInfo.value.id
    addOrUpdateForm.value.legalName = customerInfo.value.legalName
    addOrUpdateForm.value.legalPhone = customerInfo.value.legalPhone
    addOrUpdateForm.value.isNew = customerInfo.value.isNew
    addOrUpdateForm.value.industryTypeCode = customerInfo.value.industryTypeCode
    addOrUpdateForm.value.marketingPerson = customerInfo.value.marketingPerson
    addOrUpdateForm.value.marketingCompany = customerInfo.value.marketingCompany

    addOrUpdateForm.value.customerName = row.customerName
    addOrUpdateForm.value.customerTaxcode = row.customerTaxcode
    customerDialogClose()
  }
}

/**
 * 客户单击选择
 */
const handleCustomerRowClick = row => {
  customerInfo.value = row
}

/**
 * 金融客户选择事件
 */
const customerChange = () => {
  console.info('customerInfo', customerInfo.value)
  if (customerInfo.value.id == '') {
    proxy.$modal.msgWarning('请选择客户')
    return
  }
  addOrUpdateForm.value.customerId = customerInfo.value.id
  addOrUpdateForm.value.legalName = customerInfo.value.legalName
  addOrUpdateForm.value.legalPhone = customerInfo.value.legalPhone
  addOrUpdateForm.value.isNew = customerInfo.value.isNew
  addOrUpdateForm.value.industryTypeCode = customerInfo.value.industryTypeCode
  addOrUpdateForm.value.marketingPerson = customerInfo.value.marketingPerson
  addOrUpdateForm.value.marketingCompany = customerInfo.value.marketingCompany
  addOrUpdateForm.value.customerName = customerInfo.value.customerName
  addOrUpdateForm.value.customerTaxcode = customerInfo.value.customerTaxcode
  customerDialogClose()
}

/**
 * 根据当前用户回填归属人员表单
 */
async function getDefaultUserInfo(userId) {
  let params = {
    dept: ''
  }
  if (queryForm.value.orgId != 484) {
    params.dept = queryForm.value.orgId
  }
  //获取部门人员数据
  const deptUserData = await commonStore.getUseTreeData(params)

  //根据当前用户id获取uuid
  let obj = getTreeNodeByParam(deptUserData, userId, 'id', [])
  selectOptionObj.value.customerUserId = obj
  customerForm.value.marketingPerson = obj[0].uuid
}

/**
 * 修改金融客户
 */
const handleCustomerUpdate = row => {
  let params = { id: row.id }
  getBizloancustomerInfo(params).then(res => {
    customerForm.value = res.data
    customerForm.value.marketingCompany = parseInt(res.data.marketingCompany)
    getDefaultUserInfo(res.data.marketingPerson)
    customerDialogObj.value.type = 'handle'
    customerDialogObj.value.title = '修改金融客户'
    customerDialogObj.value.width = '60%'
    customerDialogObj.value.visible = true
  })
}

/**
 * 删除金融商贷客户
 */
const handleCustomerDel = row => {
  proxy.$modal
    .confirm('是否删除客户数据？')
    .then(res => {
      const params = {
        ids: row.id
      }
      bizloancustomerDel(params).then(res => {
        if (res.data != null) {
          proxy.$modal.msgError(res.msg + '，无法按删除')
          return
        } else {
          proxy.$modal.msgSuccess('删除成功')
        }
        //查询金融客户列表
        handleQueryCustomerList()
      })
    })
    .catch(() => {})
}

/**
 * 金融客户新增修改保存
 */
const handleCustomerSave = () => {
  proxy.$refs.customerFormRef.validate((valid, fields) => {
    if (valid) {
      let params = JSON.parse(JSON.stringify(customerForm.value))
      // 获取查询到的user数据对象
      let userObj = getUniqueUserId(
        selectOptionObj.value['customerUserId'],
        customerForm.value.marketingPerson
      )
      params.marketingPerson = userObj.id
      params.userId = userStore.user.userId
      params.orgId = userStore.user.orgId
      params.deptId = userStore.user.deptId
      // 金融商贷客户保存
      bizloancustomerSave(params).then(res => {
        proxy.$modal.msgSuccess(params.id ? '修改成功' : '新增成功')
        // 关闭新增金融客户表单
        handleCancalCustomerForm()
        //查询金融客户列表
        handleQueryCustomerList()
      })
    } else {
    }
  })
}

/**
 * 新增客户
 */
const handleAddCustomer = () => {
  customerDialogObj.value.type = 'handle'
  customerDialogObj.value.title = '新增金融客户'
  customerDialogObj.value.width = '60%'
}

/**
 * 取消客户表单
 */
const handleCancalCustomerForm = () => {
  customerDialogObj.value.type = 'list'
  customerDialogObj.value.title = '金融客户列表'
  customerDialogObj.value.width =
    openCustomerListType == 'select' ? '60%' : '80%'
  customerForm.value = {}
}

/**
 * 金融商贷客户列表查询
 */
const handleQueryCustomerList = () => {
  customerTableObj.value.pageNum = 1
  handleGetCustomerList()
}

/**
 * 获取金融商贷客户列表
 */
const handleGetCustomerList = () => {
  let params = {
    pageNum: customerTableObj.value.pageNum,
    pageSize: customerTableObj.value.pageSize,
    customerName: customerTableObj.value.customerName,
    customerTaxcode: customerTableObj.value.customerTaxcode
  }
  //   2个大领导
  if (
    userStore.user.userName == '3500015' ||
    userStore.user.userName == '3500025'
  ) {
  } else if (
    userStore.user.roles.findIndex(item => item.roleKey == 'jrsd_fgs_gl') != -1
  ) {
    //  分公司领导身份
    params.createBy = userStore.user.userName
    params.roleCode = 'jrsd_fgs_gl'
  } else {
    //   其余人员
    params.createBy = userStore.user.userName
  }

  getBizloancustomerList(params).then(res => {
    customerTableObj.value.tableData = res.data.records
    customerTableObj.value.total = res.data.total
  })
}

/**
 * 选择客户
 */
const handleSelectCustomer = type => {
  openCustomerListType.value = type //打开客户列表的类型
  if (type == 'select') {
    customerDialogObj.value.width = '60%'
  } else {
    customerDialogObj.value.width = '80%'
  }
  customerDialogObj.value.visible = true
  proxy.$nextTick(() => {
    handleQueryCustomerList()
  })
}

/**
 * 弹窗选取获取选中的值
 * @param val
 *  type 业务类型
 *     selectData 选中的数据[{value: 1, label: '王晓易', $treeNodeId: 2}]
 *     labelData 选中的数据label ['王晓易']
 *     defaultCheckedKeys 选中的数据id [1]
 *     dialogVisible: false 弹出框的关闭
 */
function selectData(val) {
  console.info('val', val)
  //所属人员
  if (val.type == 'userId') {
    if (!val.selectData.length) {
      queryForm.value[val.type] = ''
    } else {
      selectOptionObj.value[val.type] = val.selectData
      queryForm.value[val.type] = val.defaultCheckedKeys[0]
    }
  }
  // 客户创建获客人员
  if (val.type == 'customerUserId') {
    if (!val.selectData.length) {
      customerForm.value['marketingPerson'] = ''
    } else {
      selectOptionObj.value[val.type] = val.selectData
      customerForm.value['marketingPerson'] = val.defaultCheckedKeys[0]
    }
  }
  // 搜索条件获客人员
  if (val.type == 'searchMarketingPerson') {
    if (!val.selectData.length) {
      queryForm.value['marketingPerson'] = ''
    } else {
      selectOptionObj.value[val.type] = val.selectData
      queryForm.value['marketingPerson'] = val.defaultCheckedKeys[0]
    }
  }
}

/**
 * 新建商贷与审核弹窗保存
 */
function dialogConfirm() {
  if (dialogObj.value.type == 'handle') {
    proxy.$refs.addOrUpdateFormRef.validate((valid, fields) => {
      if (valid) {
        let params = JSON.parse(JSON.stringify(addOrUpdateForm.value))
        console.info('params', addOrUpdateForm.value)
        if (params.lendingTime && params.lendingTime != '') {
          params.lendingStarttime = params.lendingTime + ' 00:00:00'
          // params.lendingEndtime = params.lendingTime[1] + ' 23:59:59'
        } else {
          params.lendingStarttime = undefined
          // params.lendingEndtime = undefined
        }
        delete params.lendingTime
        params.userId = userStore.user.userId
        params.orgId = userStore.user.orgId
        params.deptId = userStore.user.deptId
        if (!params.id) {
          params.status = '2'
        }

        customerapplySaveOrUpdate(params).then(res => {
          proxy.$modal.msgSuccess(params.id ? '修改成功' : '新增成功')
          handleCloseDialog()
          getList()
        })
      } else {
      }
    })
  }
  if (dialogObj.value.type == 'approve') {
    let params = JSON.parse(JSON.stringify(appreveForm.value))
    customerapplySaveOrUpdate(params).then(res => {
      proxy.$modal.msgSuccess('审核成功')
      handleCloseDialog()
      getList()
    })
  }
}

function getParamsForDialogSave() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择数据')
    return
  }
  console.info(selectionData.value)
  const array = selectionData.value.map(item => {
    return {
      statusDescription: statusDescription.value,
      id: item.id,
      status: '8',
      userId: '0',
      userName: '-'
    }
  })
  return array
}

/**
 * 归属人员input获取焦点事件
 */
function userInputFocus() {
  dialogParam.value.type = 'userId'
  dialogParam.value.title = '选择人员'
  dialogParam.value.dataType = 'person'
  dialogParam.value.multiple = false
  dialogParam.value.checkStrictly = false
  dialogParam.value.nodeKey = 'id'
  let deptId = ''
  // 3500025 陈文昌  3500015 陈丽莎
  if (
    queryForm.value.orgId == '' &&
    (userStore.user.userName == '3500015' ||
      userStore.user.userName == '3500025')
  ) {
    deptId = ''
  } else {
    deptId = queryForm.value.orgId
  }

  dialogParam.value.apiParams = { deptId: deptId }

  selectOptionObj.value['userId'] = []

  // 有默认值
  if (queryForm.value['userId'] && queryForm.value['userId'].length) {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = [queryForm.value['userId']]
  } else {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = []
  }
}

/**
 * 搜索获客人员input获取焦点事件
 */
function searchMarketingPersonInputFocus() {
  dialogParam.value.type = 'searchMarketingPerson'
  dialogParam.value.title = '选择人员'
  dialogParam.value.dataType = 'person'
  dialogParam.value.multiple = false
  dialogParam.value.checkStrictly = false
  dialogParam.value.nodeKey = 'id'
  let deptId = queryForm.value.orgId

  dialogParam.value.apiParams = { deptId: deptId }

  selectOptionObj.value['searchMarketingPerson'] = []

  // 有默认值
  if (
    queryForm.value['marketingPerson'] &&
    queryForm.value['marketingPerson'].length
  ) {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = [queryForm.value['marketingPerson']]
  } else {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = []
  }
}

/**
 * 客户获客人员input获取焦点事件
 */
function customerUserInputFocus() {
  dialogParam.value.type = 'customerUserId'
  dialogParam.value.title = '选择人员'
  dialogParam.value.dataType = 'person'
  dialogParam.value.multiple = false
  dialogParam.value.checkStrictly = false
  dialogParam.value.nodeKey = 'uuid'
  let deptId = ''
  if (queryForm.value.orgId != 484) {
    deptId = queryForm.value.orgId
  }
  dialogParam.value.apiParams = { deptId: deptId }

  selectOptionObj.value['customerUserId'] = []

  // 有默认值
  if (
    customerForm.value['marketingPerson'] &&
    customerForm.value['marketingPerson'].length
  ) {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = [
      customerForm.value['marketingPerson']
    ]
  } else {
    dialogParam.value.isDialog = true
    dialogParam.value.defaultCheckedKeys = []
  }
}

/**
 * 获取归属公司数据
 * @returns {Promise<void>}
 */
async function getCompany() {
  let params = { deptType: 1 }
  if (
    userStore.user.userName == '3500015' ||
    userStore.user.userName == '3500025'
  ) {
    // 所属单位列表
    let response = await treeselectNoPriv(params)
    companyOptions.value = response.data
    formCompanyOptions.value = response.data
  } else {
    if (userStore.user.orgId !== '484') {
      queryForm.value.orgId = userStore.user.orgId * 1
    }
    // 所属单位列表
    let response = await treeselect(params)
    companyOptions.value = response.data

    // 所属单位列表
    let responseNoPriv = await treeselectNoPriv(params)
    formCompanyOptions.value = responseNoPriv.data
  }
}

/**
 * 获取商贷列表
 */
function getList() {
  loading.value = true
  let params = JSON.parse(JSON.stringify(queryForm.value))
  //   放款时间
  if (lendingTime.value != null && lendingTime.value.length > 0) {
    params.lendingStarttime = lendingTime.value[0] + ' 00:00:00'
    params.lendingEndtime = lendingTime.value[1] + ' 23:59:59'
  } else {
    params.lendingStarttime = undefined
    params.lendingEndtime = undefined
  }
  // 申请时间
  if (applyforTime.value != null && applyforTime.value.length > 0) {
    params.applyTimeStart = applyforTime.value[0] + ' 00:00:00'
    params.applyTimeEnd = applyforTime.value[1] + ' 23:59:59'
  } else {
    params.applyTimeStart = undefined
    params.applyTimeEnd = undefined
  }
  // params.orgId =  userStore.user.orgId != 484 ? userStore.user.orgId : 484
  delete params.applyTime
  delete params.lendingTime
  console.info('params', params)
  getCustomerapplyList(params)
    .then(res => {
      if (res.data != null) {
        tableData.value = res.data.records
        total.value = res.data.total
      } else {
        tableData.value = []
        total.value = 0
      }
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 弹窗关闭
 */
function handleCloseDialog() {
  // 表单
  if (dialogObj.value.type == 'handle') {
    addOrUpdateForm.value = {}
    customerInfo.value = { id: '' }
  }
  //审批
  if (dialogObj.value.type == 'approve') {
    appreveForm.value = {}
  }
  dialogObj.value.type = 'handle'

  dialogObj.value.visible = false
}

/**
 * 弹窗开启操作
 * @param type 弹窗组件类型
 *
 */
function handleOpenDialog(type) {
  // 审核
  if (type == 'approve') {
    if (!selectionData.value.length) {
      proxy.$modal.msgWarning('请选择要审核的数据')
      return
    }
    if (selectionData.value.length > 1) {
      proxy.$modal.msgWarning('只能审核一条数据')
      return
    }
    console.info('selectionData', selectionData.value)
    let params = {
      id: selectionData.value[0].id
    }
    getCustomerapplyInfo(params).then(res => {
      appreveForm.value.id = res.data.id
      appreveForm.value.customerName = res.data.customerName
      appreveForm.value.status = res.data.status
      appreveForm.value.remark = res.data.remark
    })
  }
  addOrUpdateForm.value = {}
  dialogObj.value.title = type == 'handle' ? '新增商贷' : '商贷审批'
  dialogObj.value.type = type
  dialogObj.value.visible = true
}

/**
 * 表格多选
 */
function handleSelectionChange(val) {
  selectionData.value = val
  console.info('selectionData', selectionData)
}

/**
 * 查询
 */
function handleQuery() {
  queryForm.value.pageNum = 1
  getList()
}

/**
 * 客户编辑
 */
function toUpdate() {
  if (!selectionData.value.length) {
    proxy.$modal.msgWarning('请选择要编辑的数据')
    return
  }
  if (selectionData.value.length > 1) {
    proxy.$modal.msgWarning('只能编辑一条数据')
    return
  }
  if (selectionData.value[0].status == '审核无误') {
    proxy.$modal.msgWarning('已审核的数据无法编辑')
    return
  }
  let params = { id: selectionData.value[0].id }
  getCustomerapplyInfo(params).then(res => {
    handleOpenDialog('handle')
    addOrUpdateForm.value = res.data
    // addOrUpdateForm.value.lendingTime = [
    //   res.data.lendingStarttime,
    //   res.data.lendingEndtime
    // ]
    addOrUpdateForm.value.lendingTime = res.data.lendingStarttime

    getBizloancustomerInfo({ id: res.data.customerId }).then(res => {
      addOrUpdateForm.value.customerId = res.data.id
      addOrUpdateForm.value.legalName = res.data.legalName
      addOrUpdateForm.value.legalPhone = res.data.legalPhone
      addOrUpdateForm.value.isNew = res.data.isNew
      addOrUpdateForm.value.industryTypeCode = res.data.industryTypeCode
      addOrUpdateForm.value.marketingPerson = res.data.marketingPerson
      addOrUpdateForm.value.marketingCompany = res.data.marketingCompany
      addOrUpdateForm.value.customerName = res.data.customerName
      addOrUpdateForm.value.customerTaxcode = res.data.customerTaxcode
    })

    console.info('res', res)
  })
}

/**
 * 跳转详情
 * @param row 行数据
 */
function goDetails(row) {
  router.push({
    path: '/customerManage/customerModules/customerDetails',
    query: { customerId: row.id }
  })
}

/**
 * 用户自定义显示列
 */
const getUserDefinedColumn = () => {
  customerapplyUserDefined().then(res => {
    console.info('res', res)

    const indexMap = res.data.reduce((map, key, index) => {
      map[key] = index
      return map
    }, {})
    tableColumn.value.sort((a, b) => indexMap[a.prop] - indexMap[b.prop])
    console.info('tableColumn.value', tableColumn.value)

    tableColumn.value.forEach((item, index) => {
      item.id = index
      if (res.data.includes(item.prop)) {
        // 是否选中
        item.isCheckBox = true
      }
    })
  })
}

/**
 * 获取默认创建人
 */
function getDefaultUserId() {
  //   获取默认创建人
  getDeptStaffTreeData({
    deptId: userStore.user.dept.deptId
  }).then(res => {
    console.info('1234', res)
    if (res.data.length > 0) {
      res.data.forEach(item => {
        item.children.forEach(user => {
          if (user.id == userStore.user.userId) {
            selectOptionObj.value.userId = [user]
          }
        })
      })
    }
  })
}

// 获取所有字典数据
function getAllDict() {
  let params = {
    dictType: 'lending_bank'
  }
  getDictsNew(params).then(resp => {
    lendingBankOptions.value = resp.data.map(p => ({
      label: p.dictLabel,
      value: p.dictValue,
      elTagType: p.listClass,
      elTagClass: p.cssClass,
      parentId: p.parentId,
      remark: p.remark
    }))
  })
}

// 获取客户挖掘方式字典数据
function getCustomerExcavationDict() {
  let params = {
    dictType: 'customer_excavation'
  }
  getDictsNew(params).then(resp => {
    customerExcavationOptions.value = resp.data.map(p => ({
      label: p.dictLabel,
      value: p.dictValue,
      elTagType: p.listClass,
      elTagClass: p.cssClass,
      parentId: p.parentId,
      remark: p.remark
    }))
  })
}

/**
 * 初始化
 */
function init() {
  // 部门领导
  if (
    userStore.user.roles.findIndex(item => item.roleKey == 'jrsd_fgs_gl') !=
      -1 ||
    userStore.user.userName == '3500015' ||
    userStore.user.userName == '3500025'
  ) {
    userSelectDisabled.value = false
  }

  //   获取所有银行字典数据（包含停用）
  getAllDict()
  //    客户挖掘
  getCustomerExcavationDict()
  if (
    userStore.user.userName != '3500015' &&
    userStore.user.userName != '3500025'
  ) {
    queryForm.value.userId = userStore.user.userId
    queryForm.value.orgId = userStore.user.orgId
    getDefaultUserId()
  }

  // 获取归属公司数据
  getCompany()
  //获取自定义显示列
  getUserDefinedColumn()

  proxy.$nextTick(() => {
    //申贷列表
    getList()
  })
}

init()

/**
 * 重置
 */
async function handleEmpty() {
  lendingTime.value = []
  applyforTime.value = []
  proxy.$refs.queryFormRef.resetFields()
  queryForm.value = {
    pageNum: 1,
    pageSize: 10,
    customerNameOrNumber: '',
    phoneAndNameContact: '',
    orgId: userStore.user.orgId,
    userId: userStore.user.userId
  }
  if (
    userStore.user.userName == '3500015' ||
    userStore.user.userName == '3500025'
  ) {
    queryForm.value.userId = ''
    queryForm.value.orgId = ''
  }

  await getList()
}
</script>

<style scoped lang="scss">
.customerList {
  .el-drawer .avue-form {
    @apply p-0;
  }
}
</style>
